package com.yz.arithmetic;

/**
 * 查找
 * @author yuanzheng
 * @date 2020/9/24-14:49
 */
public class BiSearch {
    public static void main(String[] args) {
        int[] array = {1, 3, 5, 7, 9, 11, 13};
        int i = biSearch(array, 13);
        System.out.println("-----" + i + "-----" + array[i - 1]);
    }

    public static int biSearch(int[] array, int a) {
        int current = 0;
        int length = array.length - 1;
        int mid;
        while (current <= length) {
            //中间位置
            mid = (current + length) / 2;
            if (array[mid] == a) {
                return mid + 1;
            } else if (array[mid] < a) {
                //向右查找
                current = mid + 1;
            } else {
                //向左查找
                length = mid - 1;
            }
        }
        return -1;
    }
}
